package com.ziq.zcamp.dialog.share

import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.bean.place.PlaceDetail
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.databinding.LayoutSharePicCachePlaceBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.io.IOUtils
import java.io.FileOutputStream

class SharePicCacheLayoutPlace @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCachePlaceBinding = LayoutSharePicCachePlaceBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""
    var placeDetail: PlaceDetail? = null

    val miniPagePath = "subpages/camp/camp-detail/index"

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    fun setPlaceData(data: PlaceDetail){
        placeDetail = data
        way = "place"
        binding.containerPlace.visibility = View.VISIBLE
        binding.qrCodeBottomTxt.text = "识别二维码 阅读完整营地信息"
        data.camp?.let {
            binding.placeName.text = it.camp_name
            val isFieldCamp = it.camp_type == 2
            if(isFieldCamp){
                binding.tvLocation.text = "打开小程序解锁地址"
            } else {
                binding.tvLocation.text = it.location_addr
            }

            if(it.images != null){
                val length = it.images!!.size
                val imageUrlOne = it.images?.get(0)?.source?:(it.images?.get(0)?.url?:"")
                binding.imagePlaceSingle.setImageURI(imageUrlOne)
                if(imageUrlOne.isNotEmpty()){
                    imageList.add(imageUrlOne)
                }
                if(length > 3){
                    binding.llPlaceFourImage.visibility = View.VISIBLE
                    val imageUrlTwo = it.images?.get(1)?.source?:(it.images?.get(1)?.url?:"")
                    val imageUrlThree = it.images?.get(2)?.source?:(it.images?.get(2)?.url?:"")
                    val imageUrlFour = it.images?.get(3)?.source?:(it.images?.get(3)?.url?:"")
                    binding.imagePlaceOne.setImageURI(imageUrlOne)
                    binding.imagePlaceTwo.setImageURI(imageUrlTwo)
                    binding.imagePlaceThree.setImageURI(imageUrlThree)
                    binding.imagePlaceFour.setImageURI(imageUrlFour)
                    if(imageUrlTwo.isNotEmpty()){
                        imageList.add(imageUrlTwo)
                    }
                    if(imageUrlThree.isNotEmpty()){
                        imageList.add(imageUrlThree)
                    }
                    if(imageUrlFour.isNotEmpty()){
                        imageList.add(imageUrlFour)
                    }
                }
            }
        }
        UserManager.instance.apply {
            if(isLogin.value == true){
                binding.llHasUserInfo.visibility = View.VISIBLE
                binding.tvNoUserInfo.visibility = View.GONE
                binding.myName.text = userInfo.value?.nick_name
                val url = userInfo.value?.header_img?:""
                binding.myAvator.setImageURI(url)
                if(url.isNotEmpty()){
                    imageList.add(url)
                }
            }
        }

        getSanCode(finish = { minCodeUrl, bitmap ->
            if(minCodeUrl.isNotEmpty()){
                imageList.add(minCodeUrl)
            }
            isScanCodeSuccess = true
        })


    }

    var isScanCodeSuccess = false
    fun getSanCode(finish: ((minCodeUrl:String, bitmap: Bitmap?) -> Unit)? = null){
        val url = "${H5Url.PLACE_DETAIL.url}?id=${placeDetail?.camp?.id?:""}${uidSuffix}"
        ShareUtil.getSanCode(MiniACodeParam().apply {
            is_hyaline = true
            page = miniPagePath
            scene = "id=${placeDetail!!.camp?.id}${uidSuffix}&share_cv="
            width = 280.toString()
        }, url,  onSuccess = { minCodeUrl:String, bitmap: Bitmap->
            binding.qrCode.post {
                binding.qrCode.setImageBitmap(bitmap)
            }
            finish?.invoke(minCodeUrl, bitmap)
            if(minCodeUrl.isNotEmpty()){
                binding.qrCodeBottomTxt.text = "识别小程序码 阅读完整内容"
            } else {
                binding.qrCodeBottomTxt.text = "识别二维码 阅读完整内容"
            }
        }, onFail = {
            finish?.invoke("", null)
        })
    }

    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        if(isScanCodeSuccess){
            callback()
        } else {
            getSanCode(finish = { minCodeUrl, bitmap->
                callback()
            })
        }
    }

    override fun getMiniProgramPath(): String {
        if(placeDetail != null){
            return "/$miniPagePath?id=${placeDetail!!.camp?.id}${uidSuffix}"
        }
        return "/pages/community/index"
    }

    override fun getTotalLayoutBitmap(): Bitmap? {
        binding.llMyUserInfo.visibility = View.GONE
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_667))
    }

    override fun getTitleForMiniProgram(): String {
        if(placeDetail != null){
            return placeDetail?.camp?.camp_name?:""
        }
        return ""
    }

    override fun getCoverBitmapForMiniProgram(action: (bitmap: Bitmap?) -> Unit) {
        binding.llMyUserInfo.visibility = View.VISIBLE
        val bitmap = ImageUtil.convertViewToBitmap(binding.flPlaceImageSingle,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_360),
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_360))
        action.invoke(bitmap)
    }

    override fun getLinkTxt(): String {
        if(placeDetail != null){
            val url = "${H5Url.PLACE_DETAIL.url}?id=${placeDetail?.camp?.id?:""}"
            return "「觅野CAMP」${placeDetail?.camp?.camp_name?:""}，等你来探~\n $url"
        }
        return ""
    }

    override fun onSavePicToLocal(source:String,finish: () -> Unit) {
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }


    private fun savePicToLocal(source:String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = GlobalContextManager.getString(R.string.share_save_success_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}